﻿#region

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Vin.Extension.JwtBearer.Extension;
using Vin.Extension.JwtBearer.Tool;
using Vin.Tool.AspNetCore.Extension;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.JsonCategory;
using Vin.Tool.Domain.ExceptionModel;

#endregion

namespace Vin.Extension.JwtBearer.Attributes;

[AttributeUsage(AttributeTargets.All)]
public class VinJwtAuthorizeAttribute : VinJwtIsAuthorizeAttribute
{
    /// <summary>
    /// 终端类型
    /// </summary>
    public string? TerminalType { get; set; }

    public string? TokenPrefix { get; set; }

    public override void OnAuthorization(AuthorizationFilterContext context)
    {
        base.OnAuthorization(context);
        if (context.Result != null) return;

        #region 判断是否有此token

        // 判断是否有此token
        var model = VinSecurityTool.GetTokenModelByToken(TokenPrefix);
        if (model == null)
        {
            context.Unauthorized();
            return;
        }

        #endregion

        #region 判断终端类型
        
        // 判断终端类型
        if (!string.IsNullOrWhiteSpace(TerminalType) && model.TerminalType != TerminalType)
        {
            context.Forbidden();
            return;
        }

        #endregion

        // 判断是否有不在token中的claim
        context.HttpContext.AddClaimsToHttpContext(model.Claims);
    }
}